package tech.xs.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tech.xs.common.framework.domain.constant.Symbol;
import tech.xs.common.framework.service.CrudServiceImpl;
import tech.xs.common.sys.domain.constant.SysCacheKeyConstant;
import tech.xs.sys.dao.SysConfigDao;
import tech.xs.sys.domain.bo.config.ImportExportConfigBo;
import tech.xs.sys.domain.entity.SysConfig;
import tech.xs.sys.service.SysConfigService;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class SysConfigServiceImpl extends CrudServiceImpl<SysConfigDao, SysConfig> implements SysConfigService {

    @Resource
    private RedissonClient redissonClient;

    @Override
    public void deleteConfigCache() {
        redissonClient.getKeys().deleteByPattern(SysCacheKeyConstant.SYS_CONFIG_CACHE + Symbol.ASTERISK);
    }

    @Override
    public void deleteConfigCache(String code) {
        redissonClient.getBucket(SysCacheKeyConstant.SYS_CONFIG_CACHE + code).delete();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importConfig(List<ImportExportConfigBo> importDatas) {
        for (ImportExportConfigBo importData : importDatas) {
            boolean isExist = count(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getCode, importData.getCode())) > 0;
            if (isExist) {
                update(Wrappers.<SysConfig>lambdaUpdate()
                        .set(SysConfig::getName, importData.getName())
                        .set(SysConfig::getData, importData.getData())
                        .set(StrUtil.isNotBlank(importData.getRemark()), SysConfig::getRemark, importData.getRemark())
                        .set(StrUtil.isBlank(importData.getRemark()), SysConfig::getRemark, null)
                        .eq(SysConfig::getCode, importData.getCode())
                );
                deleteConfigCache(importData.getCode());
            } else {
                SysConfig saveData = new SysConfig();
                saveData.setCode(importData.getCode());
                saveData.setName(importData.getName());
                saveData.setData(importData.getData());
                saveData.setRemark(importData.getRemark());
                save(saveData);
            }
        }
    }


}
